package com.study.tree;

/**
 * TrieDemo
 */
public class Trie {

    public static TrieNode root = new TrieNode();
    // add the word to Tire
    public static void add(String word){
        if (word==null){
            return;
        }
        TrieNode trieNode = root;
        char[] chars = word.toCharArray();
        trieNode.pass++;

        for (char aChar : chars) {
            int index = aChar - 'a';
            if (trieNode.trieNodes[index] == null) {
                trieNode.trieNodes[index] = new TrieNode();
            }
            trieNode = trieNode.trieNodes[index];
            trieNode.pass++;
        }
        trieNode.end++;
    }
    // search times of the word that added
    public static int search(String word){
        if (word == null){
            return 0;
        }
        char[] chars = word.toCharArray();
        TrieNode trieNode = root;
        for (int i = 0; i <chars.length ; i++) {
            int index = chars[i] - 'a';
            if (trieNode.trieNodes[index] == null){
                return 0;
            }
            trieNode = trieNode.trieNodes[index];
        }
        return trieNode.end;
    }

    // Query the number of strings prefixed with the word
    public static int searchPrefixTimes(String word){
        if (word == null){
            return 0;
        }
        TrieNode trieNode = root;
         char[] chars =  word.toCharArray();

        for (int i = 0; i <chars.length ; i++) {
            int index = chars[i] - 'a';

            if (trieNode.trieNodes[index] == null){
                return 0;
            }
            trieNode = trieNode.trieNodes[index];

        }
        return trieNode.pass;
    }
    public  static  void deleteWord (String word){
        if (word==null){
            return;
        }
        TrieNode trieNode = root;

        if (Trie.search(word)==0){
            return;
        }
        trieNode.pass--;
        char [] chars = word.toCharArray();

        for (int i = 0; i <chars.length ; i++) {
            if (trieNode.pass == 0){
                trieNode = null;
                return;
            }
            int index  = chars[i] - 'a';
            trieNode = trieNode.trieNodes[index];
            trieNode.pass--;
        }
        trieNode.end--;

    }
}
